package com.phpxiu.app.view;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.controller.avcontroller.QavsdkControl;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.LoginModeContent;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.event.WeiXinEvent;
import com.phpxiu.app.model.response.LoginMode;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.push.MessageEvent;
import com.phpxiu.app.push.PushUtil;
import com.phpxiu.app.view.custom.FrescoImageView;
import com.phpxiu.app.view.custom.InterceptRelativeLayout;
import com.phpxiu.app.view.custom.WindowLayout;
import com.tencent.TIMCallBack;
import com.tencent.TIMManager;
import com.tencent.TIMOfflinePushSettings;
import com.tencent.TIMUser;
import com.tencent.av.sdk.AVError;
import com.tencent.bugly.imsdk.crashreport.CrashReport;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * @file
 * @brief 登录方式选择界面
 * @author 吴金洲
 * @note 登录方式选择界面
 *
 */
public class Login extends BaseLogin implements View.OnClickListener,TIMCallBack {
    public final static String TAG="Login";
    private WindowLayout mainView;
    private FrescoImageView bgImageView;
    private RelativeLayout wbBtn,wxBtn,qqBtn,faceBookBtn,twitterBtn,instBtn,googleBtn;
    private TextView phoneBtn;
    private InterceptRelativeLayout coverView;
    private AnimationDrawable loading;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        EventBus.getDefault().register(this);
        bgImageView=(FrescoImageView)findViewById(R.id.ui_login_image_bg);
        bgImageView.setImageURI(Uri.parse("res:///" + R.drawable.ui_login_image_bg));
        mainView=(WindowLayout)findViewById(R.id.login_root_view);
        init();
    }

    /**
     * 初始化
     */
    private void init(){
        coverView=(InterceptRelativeLayout)findViewById(R.id.login_cover_view);
        loading=(AnimationDrawable)findViewById(R.id.loading_image_view).getBackground();
        wbBtn=(RelativeLayout)findViewById(R.id.ui_login_wb_btn);
        wbBtn.setOnClickListener(this);
        wxBtn=(RelativeLayout)findViewById(R.id.ui_login_wx_btn);
        wxBtn.setOnClickListener(this);
        qqBtn=(RelativeLayout)findViewById(R.id.ui_login_qq_btn);
        qqBtn.setOnClickListener(this);
        faceBookBtn=(RelativeLayout)findViewById(R.id.ui_login_fb_btn);
        faceBookBtn.setOnClickListener(this);
        twitterBtn=(RelativeLayout)findViewById(R.id.ui_login_tw_btn);
        twitterBtn.setOnClickListener(this);
        instBtn=(RelativeLayout)findViewById(R.id.ui_login_inst_btn);
        instBtn.setOnClickListener(this);
        googleBtn=(RelativeLayout)findViewById(R.id.ui_login_google_btn);
        googleBtn.setOnClickListener(this);
        phoneBtn=(TextView)findViewById(R.id.ui_login_phone_btn);
        phoneBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ui_login_wb_btn:
                loginSina();
                break;
            case R.id.ui_login_wx_btn:
                loginWX();
                break;
            case R.id.ui_login_qq_btn:
                loginQQ();
                break;
            case R.id.ui_login_fb_btn:
                loginFaceBook();
                break;
            case R.id.ui_login_tw_btn:
                loginTwitter();
                break;
            case R.id.ui_login_inst_btn:
                loginInst();
                break;
            case R.id.ui_login_google_btn:
                loginGooglePlus();
                break;
            case R.id.ui_login_phone_btn:
                Intent phone=new Intent(this,LoginByPhone.class);
                startActivityForResult(phone,ACCOUNT_LOGIN_REQUEST_CODE);
                break;
            default:
                break;
        }
    }

    @Override
    protected void loginStart() {
        super.loginStart();
        if(coverView.getVisibility()!=View.VISIBLE){
            coverView.setVisibility(View.VISIBLE);
            if(loading!=null){
                loading.start();
            }
        }
    }

    @Override
    protected void loginErr(String msg) {
        super.loginErr(msg);
        hidePro();
        if(mainView!=null){
            mainView.showTopMsg(msg);
        }
    }

    @Override
    protected void loginComplete() {
        super.loginComplete();
        hidePro();
    }

    /**
     * 隐藏进度
     */
    private void hidePro(){
        if(coverView.getVisibility()==View.VISIBLE){
            coverView.setVisibility(View.INVISIBLE);
            if(loading!=null){
                loading.stop();
            }
        }
    }

    @Override
    protected void login(String type, String uid,String nick) {
        OKHttpParam param= OKHttpParam.builder(false);
        param.put("type",type);
        param.put("token",uid);
        param.put("secret",uid);
        param.put("nick",nick);
        OKHttp.post(HttpConfig.API_LOGIN, param.jsonParam(), TAG, new OKHttpUIHandler(LoginMode.class) {
            @Override
            public void onSuccess(Object model) {
                LoginMode m = (LoginMode) model;
                loginSuccess(m.getData());
            }

            @Override
            public void onErr(String errMsg) {
                loginErr(getString(R.string.login_failed));
            }
        });
    }

    /**
     * 微信登录
     */
    @Subscribe
    public void onWeiXinLogin(WeiXinEvent event){
        if(event.getCode()== WeiXinEvent.LOGIN_SUCCESS) {
            login(WX,event.getUnionId(),event.getNick());
            return;
        }
        if(event.getCode()== WeiXinEvent.LOGIN_ERR) {
            mainView.post(new Runnable() {
                @Override
                public void run() {
                    loginErr(getString(R.string.login_failed));
                }
            });
        }
        loginComplete();
    }

    /**
     * 登录成功结果
     * @param result
     */
    private void loginSuccess(LoginModeContent result){
        MySelfInfo.getInstance().setId(result.getUserinfo().getUid());
        MySelfInfo.getInstance().setUserSig(result.getSig());
        MySelfInfo.getInstance().setNickName(result.getUserinfo().getNickname());
        MySelfInfo.getInstance().setAvatar(result.getUserinfo().getAvatar());
        MySelfInfo.getInstance().setSign(result.getUserinfo().getIntro());
        MySelfInfo.getInstance().setCosSig(result.getCossig());
        try {
            int roomNum = Integer.parseInt(result.getUserinfo().getRoomid());
            MySelfInfo.getInstance().setMyRoomNum(roomNum);
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        MySelfInfo.getInstance().setMobilenum(result.getUserinfo().getMobilenum());
        MySelfInfo.getInstance().setSex(result.getUserinfo().getSex());
        MySelfInfo.getInstance().setAddress(result.getUserinfo().getAddress());
        MySelfInfo.getInstance().setVerifyState(result.getUserinfo().getApproved());
        try {
            MySelfInfo.getInstance().setMoney(Long.parseLong(result.getUserinfo().getMoney()));
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        try {
            MySelfInfo.getInstance().setLvl(Integer.parseInt(result.getUserinfo().getLvl()));
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        MySelfInfo.getInstance().setMerrage(result.getUserinfo().getMerrage());
        try {
            MySelfInfo.getInstance().setAge(Integer.parseInt(result.getUserinfo().getAge()));
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        MySelfInfo.getInstance().writeToCache(this);
        IMLogin(MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getUserSig());

    }

    /**
     * 登录IM
     * @param identify 用户id
     * @param userSig//登录获取的签名
     */
    private void IMLogin(String identify,String userSig){
        TIMUser user = new TIMUser();
        user.setAccountType(String.valueOf(Constants.ACCOUNT_TYPE));
        user.setAppIdAt3rd(String.valueOf(Constants.SDK_APPID));
        user.setIdentifier(identify);
        //发起登录请求
        TIMManager.getInstance().login(Constants.SDK_APPID, user, userSig, Login.this);
    }

    /**
     * IM 登录失败
     * @param i
     * @param s
     */
    @Override
    public void onError(int i, String s) {
        if(i==6012){
            //mainView.showTopMsg("初始化失败，服务登录超时");
        }
        //发送日志到错误统计
        CrashReport.postCatchedException(new Throwable("Main IM Login failed：" + i + "-->" + s));
        loginErr(getString(R.string.login_failed));
    }

    /**
     * IM登录成功
     */
    @Override
    public void onSuccess() {
        TIMOfflinePushSettings SETTINGS = new TIMOfflinePushSettings();
        SETTINGS.setEnabled(true);
        TIMManager.getInstance().configOfflinePushSettings(SETTINGS);
        //初始化程序后台后消息推送
        PushUtil.getInstance();
        //初始化消息监听
        MessageEvent.getInstance();
        if(startAVSDK()){
            Intent main=new Intent(Login.this,Main.class);
            startActivity(main);
            finish();
        }else{
            loginErr(getString(R.string.login_failed));
            CrashReport.postCatchedException(new Exception("登录失败,AV SDK初始化失败"));
        }
    }

    /**
     * 初始化音视频SDK
     */
    public static boolean startAVSDK() {
        QavsdkControl.getInstance().setAvConfig(Constants.SDK_APPID, "" + Constants.ACCOUNT_TYPE, MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getUserSig());
        int startResult=QavsdkControl.getInstance().startContext();
        if(startResult!=AVError.AV_OK){
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
